<?php

require_once "DB.class.php";

class Entidad {
	# campos de la entidad.
	protected $campos;
	# campos clave de la entidad.
	protected $clave;
	# campo autoincremental.
	protected $autoincrementar;
	# nombre de la tabla.
	protected $tabla;

	function __construct($campos, $clave, $tabla, $autoincrementar = null) {
	
		$this->campos = $campos;
		$this->clave = $clave;
		$this->autoincrementar = $autoincrementar;
		$this->tabla = $tabla;
	}
		
	protected function load($data) {
		foreach ($this->campos as $c) {
			$this->$c = (isset($data[$c])) ? $data[$c] : "";
		}	

		// Si se marco autoincremnt y la clave es atomica. 
		if (isset($this->autoincrementar)) {
			if (!isset($data[$this->autoincrementar])) {
				$auto = $this->autoincrementar;
				$this->$auto = "NULL";
			}
		}
	}

	protected function save($update = false) {
		//create a new database object.
		$db = new DB();
		$db->connect();
		
		$data = array ();

		foreach ($this->campos as $c) {
			if ($c != $this->$autoincrementar)
				$data[$c] = $this->$c;
		}

		$exito = false;
		if ($update) {
			$exito = $db->update($data,$this->tabla,$this->clave." = ".$this->id);
			error_log(__FILE__.".UPDATE: $exito");
		} else {
			$this->id = $db->insert($data,$this->tabla);
			error_log(__FILE__.".INSERT: ".$exito."; id=".$this->id);
			$exito = ($this->id > 0);
		}
		return $exito;
	}
}
?>

